package com.feng.vhr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feng.vhr.common.RespBean;
import com.feng.vhr.pojo.*;
import com.feng.vhr.response.RHr;
import com.feng.vhr.response.Rmenu;
import com.feng.vhr.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/basic")
public class SystemController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IJoblevelService joblevelService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;

    @Autowired
    private IHrRoleService hrRoleService;

    @Autowired
    private IHrService hrService;

    /**
     * 查询部门列表
     *
     * @return
     */
    @GetMapping("/department")
    public RespBean getAllDepartment() {
        List<Department> list = departmentService.list();
        return RespBean.ok("", list);
    }

    /**
     * 添加部门
     *
     * @param department
     * @return
     */
    @PostMapping("/department")
    public RespBean addDepartment(@RequestBody Department department) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("name", department.getName());
        Department one = departmentService.getOne(wrapper);
        if (one != null) {
            return RespBean.error("此部门已存在");
        }
        boolean save = departmentService.save(department);
        if (save) {
            return RespBean.ok("添加部门成功");
        }
        return RespBean.error("添加部门失败");
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @DeleteMapping("/department/{id}")
    public RespBean deleteDepartment(@PathVariable int id) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("parentId", id);
        List<Department> list = departmentService.list(wrapper);
        if (list.size() != 0) {
            return RespBean.error("您无法删除此部门，请先删除此部门下的子级部门");
        }
        boolean b = departmentService.removeById(id);
        if (b) {
            return RespBean.ok("删除部门成功");
        }
        return RespBean.error("删除部门失败");
    }

    /**
     * 查询职位列表
     *
     * @return
     */
    @GetMapping("/pos")
    public RespBean getAllPosition() {
        List<Position> list = positionService.list();
        return RespBean.ok("", list);
    }

    /**
     * 添加职位
     *
     * @param position
     * @return
     */
    @PostMapping("/pos")
    public RespBean addPosition(@RequestBody Position position) {
        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        wrapper.eq("name", position.getName());
        Position one = positionService.getOne(wrapper);
        if (one != null) {
            return RespBean.error("此职位已存在");
        }
        boolean save = positionService.save(position);
        if (save) {
            return RespBean.ok("职位添加成功");
        }
        return RespBean.error("职位添加失败");
    }

    /**
     * 编辑职位信息
     *
     * @return
     */
    @PutMapping("/pos")
    public RespBean editPosition(@RequestBody Position position) {
        boolean update = positionService.updateById(position);
        if (update) {
            return RespBean.ok("编辑职位信息成功");
        }
        return RespBean.error("编辑职位信息失败");
    }


    /**
     * 单个删除职位
     *
     * @param id
     * @return
     */
    @DeleteMapping("/pos/{id}")
    public RespBean deletePosition(@PathVariable int id) {

        if (id != 0) {
            QueryWrapper<Employee> wrapper = new QueryWrapper<>();
            wrapper.eq("posId", id);
            List<Employee> list = employeeService.list(wrapper);
            if (list.size() != 0) {
                return RespBean.error("您无法删除此职位，请先删除此职位的员工");
            }
            boolean b = positionService.removeById(id);

            if (b) {
                return RespBean.ok("删除职位成功");
            }
        }
        return RespBean.error("删除职位失败");
    }

    /**
     * 批量删除职位
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/pos")
    public RespBean deleteSomePosition(int[] ids) {
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        if (idList != null) {
            for (Integer pid : ids) {
                QueryWrapper<Employee> wrapper = new QueryWrapper<>();
                wrapper.eq("posId", pid);
                List<Employee> list = employeeService.list(wrapper);
                if (list.size() != 0) {
                    return RespBean.error("您无法删除此职位，请先删除职位下的员工");
                }
            }
            boolean b = positionService.removeBatchByIds(idList);
            if (b) {
                return RespBean.ok("删除职位成功");
            }
        }
        return RespBean.error("删除职位失败");
    }


    /**
     * 查询职称列表
     *
     * @return
     */
    @GetMapping("/joblevel")
    public RespBean getAllJoblevel() {
        List<Joblevel> list = joblevelService.list();
        return RespBean.ok("", list);
    }

    /**
     * 添加职称
     *
     * @param joblevel
     * @return
     */
    @PostMapping("/joblevel")
    public RespBean addJoblevel(@RequestBody Joblevel joblevel) {
        QueryWrapper<Joblevel> wrapper = new QueryWrapper<>();
        wrapper.eq("name", joblevel.getName());
        Joblevel one = joblevelService.getOne(wrapper);
        if (one != null) {
            return RespBean.error("此职称已存在");
        }
        boolean save = joblevelService.save(joblevel);
        if (save) {
            return RespBean.ok("职称添加成功");
        }
        return RespBean.error("职称添加失败");
    }

    /**
     * 编辑职称
     *
     * @param joblevel
     * @return
     */
    @PutMapping("/joblevel")
    public RespBean editJoblevel(@RequestBody Joblevel joblevel) {
        boolean update = joblevelService.updateById(joblevel);
        if (update) {
            return RespBean.ok("编辑职称成功");
        }
        return RespBean.error("编辑职称失败");
    }


    /**
     * 单个删除职称
     *
     * @param id
     * @return
     */
    @DeleteMapping("/joblevel/{id}")
    public RespBean deleteJoblevel(@PathVariable int id) {
        if (id != 0) {
            QueryWrapper<Employee> wrapper = new QueryWrapper<>();
            wrapper.eq("jobLevelId", id);
            List<Employee> list = employeeService.list(wrapper);
            if (list.size() != 0) {
                return RespBean.error("您无法删除此职称，请先删除此职称的员工");
            }
            boolean b = joblevelService.removeById(id);

            if (b) {
                return RespBean.ok("删除职称成功");
            }
        }
        return RespBean.error("删除职称失败");
    }

    /**
     * 批量删除职称
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/joblevel")
    public RespBean deleteSomeJoblevel(int[] ids) {
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        if (idList != null) {
            for (Integer jid : idList) {
                QueryWrapper<Employee> wrapper = new QueryWrapper<>();
                wrapper.eq("jobLevelId", jid);
                List<Employee> list = employeeService.list(wrapper);
                if (list.size() != 0) {
                    return RespBean.error("您无法删除此职称，请先删除职称下的员工");
                }
            }
            boolean b = joblevelService.removeBatchByIds(idList);
            if (b) {
                return RespBean.ok("删除职称成功");
            }
        }
        return RespBean.error("删除职称失败");
    }


    /**
     * 查询权限列表
     *
     * @return
     */
    @GetMapping("/permiss")
    public RespBean getAllPermiss() {
        List<Role> list = roleService.list();
        return RespBean.ok("", list);
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/permiss/role")
    public RespBean addRole(@RequestBody Role role) {
        role.setName("ROLE_"+role.getName());
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("name", role.getName()).or().eq("nameZh", role.getNameZh());
        Role one = roleService.getOne(wrapper);
        if (one != null) {
            return RespBean.error("此角色已存在");
        }
        boolean save = roleService.save(role);
        if (save) {
            return RespBean.ok("添加角色成功");
        }
        return RespBean.error("添加角色失败");
    }

    /**
     * 查询所有菜单信息
     *
     * @return
     */
    @GetMapping("/permiss/menus")
    public RespBean getAllMenus() {
        List<Rmenu> menuByRole = menuService.getAllMenu();
        return RespBean.ok("", menuByRole);
    }

    /**
     * 根据角色id查询菜单id
     *
     * @param rid
     * @return
     */
    @GetMapping("/permiss/mids/{rid}")
    public RespBean getMidsByRid(@PathVariable Integer rid) {
        List<Integer> midsByRid = menuRoleService.getMidsByRid(rid);
        return RespBean.ok("", midsByRid);
    }

    /**
     * 删除角色
     * @param rid
     * @return
     */
    @Transactional
    @DeleteMapping("/permiss/role/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid) {
        QueryWrapper<HrRole> wrapper = new QueryWrapper<>();
        wrapper.eq("rid", rid);
        List<HrRole> list = hrRoleService.list(wrapper);
        if (list.size() != 0) {
            return RespBean.error("无法删除此角色，请先删除此角色下的用户");
        }
        QueryWrapper<MenuRole> menuRoleQueryWrapper = new QueryWrapper<>();
        menuRoleQueryWrapper.eq("rid", rid);
        menuRoleService.remove(menuRoleQueryWrapper);
        boolean b = roleService.removeById(rid);

        return RespBean.ok("角色删除成功");
    }


    /**
     * 修改角色的可访问资源
     * @param rid
     * @param mids
     * @return
     */
    @PutMapping("/permiss")
    public RespBean updateRole(Integer rid, Integer[] mids) {
        QueryWrapper<MenuRole> wrapper = new QueryWrapper<>();
        wrapper.eq("rid", rid);
        boolean b = menuRoleService.remove(wrapper);
        for (Integer mid : mids) {
            MenuRole menuRole = new MenuRole();
            menuRole.setMid(mid);
            menuRole.setRid(rid);
            menuRoleService.save(menuRole);
        }
        return RespBean.ok("可访问资源修改成功");
    }


    //===========================================操作员管理===============================================

    /**
     * 查询所有操作员信息
     * @param keywords
     * @return
     */
    @GetMapping("/hr")
    public RespBean getHrs(String keywords){
        List<RHr> rHrs = new ArrayList<>();
        QueryWrapper<Hr> wrapper = new QueryWrapper<>();
        if (keywords!=null){
            wrapper.like("name",keywords).or().like("address",keywords).or().like("username",keywords);
        }
        List<Hr> hrs = hrService.list(wrapper);
        List<Role> roles = new ArrayList<>();
        for (Hr hr : hrs) {
            RHr rHr = new RHr();
            List<Role> roleList = new ArrayList<>();
            QueryWrapper<HrRole> hrRoleQueryWrapper = new QueryWrapper<>();
            hrRoleQueryWrapper.eq("hrid",hr.getId());
            List<HrRole> hrRoles = hrRoleService.list(hrRoleQueryWrapper);
            for (HrRole hrRole : hrRoles) {
                Role role = roleService.getById(hrRole.getRid());
                roleList.add(role);
            }
            BeanUtils.copyProperties(hr,rHr);
            rHr.setRoles(roleList);
            rHrs.add(rHr);
        }
        return RespBean.ok("",rHrs);
    }


    /**
     * 查询所有角色信息
     * @return
     */
    @GetMapping("/hr/roles")
    public RespBean getAllRoles(){
        List<Role> list = roleService.list();
        return RespBean.ok("",list);
    }

    /**
     * 修改操作员账号状态
     * @param hr
     * @return
     */
    @PutMapping("/hr")
    public RespBean updateEnabled(@RequestBody Hr hr){
        System.out.println(hr);
        UpdateWrapper<Hr> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",hr.getId());
        if (hr.getEnabled()){
            wrapper.set("enabled",1);
        }else {
            wrapper.set("enabled",0);
        }

        hrService.update(wrapper);
        return RespBean.ok("");
    }

    /**
     * 修改操作员角色
     * @param hrid
     * @param rids
     * @return
     */
    @PutMapping("/hr/role")
    public RespBean updateRoles(Integer hrid,Integer[] rids){
        System.out.println(hrid);
        System.out.println(rids);

        QueryWrapper<HrRole> wrapper = new QueryWrapper<>();
        wrapper.eq("hrid",hrid);
        hrRoleService.remove(wrapper);

        for (Integer rid : rids) {
            HrRole hrRole = new HrRole();
            hrRole.setHrid(hrid);
            hrRole.setRid(rid);
            hrRoleService.save(hrRole);
        }
        return RespBean.ok("修改角色成功");
    }

    /**
     * 删除操作员账号
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/hr/{id}")
    public RespBean deleteHr(@PathVariable Integer id){
        QueryWrapper<HrRole> wrapper = new QueryWrapper<>();
        wrapper.eq("hrid",id);
        hrRoleService.remove(wrapper);
        hrService.removeById(id);
        return RespBean.ok("删除操作员成功");
    }

}
